#include "showtestinput.h"
#include <QFile>
#include <QTextStream>
#include <QTextCodec>
#include "sqlquery.h"


ShowTestInput::ShowTestInput(QWidget *parent, int lessontypenum, int variantnum, int modnum, int lessontypeid, int variantid, int modid, int complexityid, bool showDescr)
	: QDialog(parent)
{
	ui.setupUi(this);

	if (showDescr) {
		//create and show variant/mod description dialog
		vmtdlg = new VarModText(this, lessontypeid, variantid, modid, complexityid);
		vmtdlg->show();
	}

	//read tests.txt and populate list widget
	path = Helper::pathToTests(lessontypenum, variantnum, modnum);
	QString testsFileName = path + "tests.txt";
	QFile testsFile(testsFileName);
	if (testsFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
		QTextStream tststream(&testsFile);
		tststream.setCodec("CP1251");

		QString name,file;
		while (!tststream.atEnd()) {
			name = tststream.readLine();
			file = tststream.readLine();
			if (file == "str_unit.txt") {//unit tests
				QFile unitTestsFile(path + file);
				if (unitTestsFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
					QTextStream unittststream(&unitTestsFile);
					unittststream.setCodec("CP1251");
					while (!unittststream.atEnd()) {
						name = unittststream.readLine();
						file = unittststream.readLine();
						testnames << name;
						testfiles << file;
						ui.testList->addItem(name);
					}
				}
			} else {//black box test
				testnames << name;
				testfiles << file;
				ui.testList->addItem(name);
			}
		}
	}

	SqlQuery sq;

	//set lesson type
	SET_QUERY_DATA(lessonType,"SELECT name,id FROM lesson_types");
	if (lessontypeid != -1) {
		sq.exec(QString("SELECT name FROM lesson_types WHERE id=%1").arg(lessontypeid));
		if (sq.next())
			ui.lessonType->setCurrentIndex(ui.lessonType->findText(sq.value(0).toString()));

	}

	//set mod complexity
	SET_QUERY_DATA(modComplexity,"SELECT name,id FROM mod_complexities");
	if (complexityid != -1) {
		sq.exec(QString("SELECT name FROM mod_complexities WHERE id=%1").arg(complexityid));
		if (sq.next())
			ui.modComplexity->setCurrentIndex(ui.modComplexity->findText(sq.value(0).toString()));
	} else {
		ui.modComplexity->setCurrentIndex(-1);
	}

	//set variant number
	ui.variantNum->setValue(variantnum);

	//zoom in text
	ui.inputData->zoomIn(1);

	connect(ui.closeMe,SIGNAL(clicked()),this,SLOT(closeMe()));
	connect(ui.testList,SIGNAL(currentRowChanged(int)),this,SLOT(testSelected(int)));

}

ShowTestInput::~ShowTestInput()
{
	delete vmtdlg;

}

void ShowTestInput::testSelected(int indx)
{
	QString filename = path+testfiles[indx];
	QFile file(filename);
	QString ptext;
	if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
		QTextStream strm(&file);
		strm.setCodec("CP1251");

		while(!strm.atEnd()) {
			ptext+=strm.readLine()+"\n";
		}
	}

	ui.inputData->setPlainText(ptext);
}

void ShowTestInput::closeMe()
{
	accept();
}